Zip for WinRT > Zip for WinRT Fundamentals > Medium Level: C1ZStreamReader and C1ZStreamWriter Classes |
The C1ZStreamReader and C1ZStreamWriter classes allow you to use data compression on any .NET streams, not only in zip files.
To use C1ZStreamReader and C1ZStreamWriter objects, attach them to regular streams and read or write the data through them. The data is compressed (or expanded) on the fly into (or out of) the underlying stream.
This design allows great integration with native .NET streams. The diagram below illustrates how it works:
For example, the code below saves a DataGrid into a stream and then reads it back:
C# |
Copy Code
|
---|---|
PersonList personList = new PersonList(); public MainPage() { InitializeComponent(); } // create the DataGrid private void btnCreate_Click(object sender, RoutedEventArgs e) { for (int i = 0; i < 1000; i++) { personList.Persons.Add(new Person() { FirstName = string.Format("First Name {0}", i), LastName = string.Format("Last Name {0}", i), Age = i, City = string.Format("City {0}", i) }); } this.dataGrid1.ItemsSource = personList.Persons; } // save the data to a stream private void btnSave_Click(object sender, RoutedEventArgs e) { SaveFileDialog dlgSaveFile = new SaveFileDialog(); if (dlgSaveFile.ShowDialog() == true) { Stream stream = dlgSaveFile.OpenFile(); DataContractSerializer dcs = new DataContractSerializer(typeof(PersonList)); dcs.WriteObject(stream, personList); stream.Close(); } } // Compress the data private void btnSaveCompressed_Click(object sender, RoutedEventArgs e) { var dlgSaveFile = new SaveFileDialog(); if (dlgSaveFile.ShowDialog() == true) { Stream stream = dlgSaveFile.OpenFile(); //Use C1ZStreamWriter to compress the stream. C1ZStreamWriter compressor = new C1ZStreamWriter(stream); DataContractSerializer dcs = new DataContractSerializer(typeof(PersonList)); dcs.WriteObject(compressor, personList); stream.Close(); } } // Load the data from the stream private void btnLoad_Click(object sender, RoutedEventArgs e) { var dlgOpenFile = new OpenFileDialog(); this.dataGrid1.ItemsSource = null; if (dlgOpenFile.ShowDialog() == true) { Stream stream = dlgOpenFile.File.OpenRead(); DataContractSerializer dcs = new DataContractSerializer(typeof(PersonList)); PersonList pl = (PersonList)dcs.ReadObject(stream); stream.Close(); this.dataGrid1.ItemsSource = pl.Persons; } } // Load the compressed data private void btnLoadCompressed_Click(object sender, RoutedEventArgs e) { var dlgOpenFile = new OpenFileDialog(); this.dataGrid1.ItemsSource = null; if (dlgOpenFile.ShowDialog() == true) { Stream stream = dlgOpenFile.File.OpenRead(); DataContractSerializer dcs = new DataContractSerializer(typeof(PersonList)); //Use C1ZStreamReader to uncompress the stream. C1ZStreamReader compressor = new C1ZStreamReader(stream); PersonList pl = (PersonList)dcs.ReadObject(compressor); stream.Close(); this.dataGrid1.ItemsSource = pl.Persons; } } |